<!--
 * @Author: 陈俊升 761723995@qq.com
 * @Date: 2023-12-07 10:34:46
 * @LastEditors: 陈俊升 761723995@qq.com
 * @LastEditTime: 2024-02-18 16:21:36
 * @FilePath: /hr_new_vue3/src/views/Management/Organization/BaseSetting/PositionSystem/PositionSort/Modal.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- 职位类别-新增、编辑职位类别弹出框 -->
<template>
  <a-modal
    width="50%"
    :visible="visible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
    title-align="center"
    unmount-on-close
  >
    <template #title>
      <div>
        {{ title }}
      </div>
    </template>
    <a-form
      :model="formData.data"
      auto-label-width
      :rules="rules"
      ref="refForm"
    >
      <a-form-item label="类别名称" field="typeName" show-colon>
        <a-input
          v-model.trim="formData.data.typeName"
          :disabled="isTypeNameDisabled()"
        />
      </a-form-item>
      <a-form-item
        label="序列名称"
        field="sequenceName"
        show-colon
        v-if="isShowSequenceName()"
      >
        <a-input
          v-model.trim="formData.data.sequenceName"
          :disabled="isSequenceNameDisabled()"
        />
      </a-form-item>
      <a-form-item
        label="子序列名称"
        field="subSequenceName"
        show-colon
        v-if="isShowSubSequenceName()"
      >
        <a-input
          v-model.trim="formData.data.subSequenceName"
          :disabled="isSubSequenceName()"
        />
      </a-form-item>
      <a-form-item
        label="类别编码"
        field="code"
        show-colon
        v-if="!isTypeNameDisabled()"
      >
        <a-input v-model.trim="formData.data.code" />
      </a-form-item>
      <a-form-item label="颜色" field="color" show-colon>
        <ColorPicker v-model:color="formData.data.color"></ColorPicker>
      </a-form-item>

      <a-form-item label="启用状态" field="isEnable" show-colon>
        <a-switch
          v-model="formData.data.isEnable"
          :checked-value="1"
          :unchecked-value="2"
        />
      </a-form-item>
      <a-form-item label="备注" field="remark" show-colon>
        <a-textarea
          v-model="formData.data.remark"
          :max-length="300"
          :auto-size="{
            minRows: 3
          }"
          allow-clear
          show-word-limit
        />
      </a-form-item>
    </a-form>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk" :loading="store.isLoading"
        >确定</a-button
      >
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
import ColorPicker from '@/components/ColorPiker.vue';

import { cloneDeep } from 'lodash';
import { validateRules } from '@/utils/common';
import { CheckPositionSortList } from '@/apis/management/organization/baseSetting/PositionSystem/index';
import useGlobalParametersStore from '@/store/modules/globalParameters';

const store = useGlobalParametersStore();
const props = withDefaults(
  defineProps<{
    visible: boolean; // 是否显示对话框
    data: any;
    title: string;
    status: 'add' | 'edit';
  }>(),
  {
    visible: false
  }
);

const formData: any = reactive({
  data: {
    name: '', // 原本的名称
    typeName: '', // 类别名称
    sequenceName: '', // 序列名称
    subSequenceName: '', // 子序列名称
    code: '',
    isEnable: 1,
    remark: '',
    level: 1,
    pid: 0,
    color: '#000'
  }
});

let refForm = ref();
const emit = defineEmits(['update:visible', 'typeEmit']);

// 校验名字查重
const validateName = async (val: string, cb: any) => {
  try {
    if (val === props.data?.name && formData.data?.id > 0) {
      //
    } else {
      const data = {
        // type: 1,
        // pid: form.top === '' ? form.pid : form.id,
        name: val
      };
      const res = await validateRules(CheckPositionSortList, data);
      if (res.code) {
        cb(`${res.msg}`);
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 校验编码查重
const validateCode = async (val: string, cb: any) => {
  try {
    if (!/^[A-Z]+$/.test(val)) cb('请输入大写英文字母且不能有空格！');
    if (val === props.data?.code && formData.data.id > 0) {
      //
    } else {
      const data = {
        // type: 2,
        // pid: form.top === '' ? form.pid : form.id,
        code: val
      };
      const res = await validateRules(CheckPositionSortList, data);
      if (res.code) {
        cb(`${res.msg}`);
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

const rules = reactive({
  typeName: [
    {
      required: true,
      message: '请填写'
    },
    {
      validator:
        formData.data?.level === 1
          ? validateName
          : () => {
              return true;
            }
    }
  ],
  sequenceName: [
    {
      required: true,
      message: '请填写'
    },
    {
      validator:
        formData.data?.level === 2
          ? validateName
          : () => {
              return true;
            }
    }
  ],
  subSequenceName: [
    {
      required: true,
      message: '请填写'
    },
    {
      validator:
        formData.data?.level === 3
          ? validateName
          : () => {
              return true;
            }
    }
  ],
  code: [
    {
      required: true,
      message: '请填写'
    },
    {
      validator: validateCode
    }
  ],
  isEnable: [
    {
      required: true,
      message: '请选择'
    }
  ]
});

const returnTrue = () => true;
watch(
  () => props.visible,
  (newVal: boolean) => {
    if (newVal) {
      if (props.data?.id) {
        formData.data = cloneDeep(props.data);
      } else {
        formData.data = {
          name: '', // 原本的名称
          typeName: '', // 类别名称
          sequenceName: '', // 序列名称
          subSequenceName: '', // 子序列名称
          code: '',
          isEnable: 1,
          remark: '',
          level: 1,
          pid: 0
        };
      }
      // 根据level判断rules的查重规则
      if (formData.data?.level === 1) {
        rules.typeName[1].validator = validateName;
        rules.sequenceName[1].validator = returnTrue;
        rules.subSequenceName[1].validator = returnTrue;
      } else if (formData.data?.level === 2) {
        rules.typeName[1].validator = returnTrue;
        rules.sequenceName[1].validator = validateName;
        rules.subSequenceName[1].validator = returnTrue;
      } else if (formData.data?.level === 3) {
        rules.typeName[1].validator = returnTrue;
        rules.sequenceName[1].validator = returnTrue;
        rules.subSequenceName[1].validator = validateName;
      }
    }
  }
);

// 类别名称是否禁用
const isTypeNameDisabled = () => {
  if (props.status === 'add') {
    if (formData.data?.id) {
      return true;
    }
  } else if (props.status === 'edit') {
    if (formData.data.id && formData.data.level > 1) return true;
  }
  return false;
};

// 是否显示序列名称
const isShowSequenceName = () => {
  if (props.status === 'add') {
    if (formData.data.id && formData.data.level >= 1) return true;
  } else if (props.status === 'edit') {
    if (formData.data.id && formData.data.level > 1) return true;
  }
};

// 序列名称是否禁用
const isSequenceNameDisabled = () => {
  if (props.status === 'add') {
    if (formData.data.level === 2) {
      return true;
    }
  } else if (props.status === 'edit') {
    if (formData.data.level === 3) {
      return true;
    }
  }
  return false;
};

// 是否显示子序列名称
const isShowSubSequenceName = () => {
  if (props.status === 'add') {
    if (formData.data.id && formData.data.level >= 2) return true;
  } else if (props.status === 'edit') {
    if (formData.data.id && formData.data.level > 2) return true;
  }
};

const isSubSequenceName = () => {
  //
};

// 保存
const handleOk = async () => {
  if (await refForm.value?.validate()) return;
  emit('typeEmit', formData.data);
  emit('update:visible', false);
};

// 取消
const handleCancel = () => {
  emit('typeEmit', null);
  emit('update:visible', false);
};
</script>

<style scoped lang="less"></style>
